package com.dh.blog.controllers.admin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dh.blog.auth.AuthUtils;
import com.dh.blog.controllers.FileController;
import com.dh.blog.handler.SaveFileHandler;
import com.dh.blog.service.BlogService;
import com.dh.blog.service.FileService;
import com.dh.blog.vo.BlogVo;
import com.dh.blog.vo.MATFileVo;
import com.ewei.web.common.exception.MessageRuntimeException;
import com.ewei.web.common.json.resolver.JsonModel;
import com.ewei.web.common.json.resolver.JsonModelMap;
import com.ewei.web.common.response.ResponseVO;
import com.ewei.web.common.utils.FileToolsBar;
import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping(value="admin/mat")
public class AdminFileController {
	private final String identify = "694af96a64e711e6961d00ff8a62d83e";
	private static final Pattern pattern = Pattern.compile("/admin/mat(/[\\S]+)");
	private static final Logger logger = LogManager.getLogger(AdminFileController.class);
	@Resource
	private FileService fileService;
	@Resource
	private BlogService blogService;
	@Resource
	private Properties config;
	@Resource
	private SaveFileHandler saveFile;
	/**
	 * 读取素材文件
	 */
	@RequestMapping(value="/**",method=RequestMethod.GET)
	public void read(HttpServletRequest request,HttpServletResponse response){
		//AuthUtils.getIdentify();
		String abs = "";
		String uri = request.getRequestURI();
		Matcher matcher = pattern.matcher(uri);
		if(matcher.find()){
			abs = matcher.group(1);
		}
		MATFileVo mat = fileService.getMATFile(abs);//获得素材文件的vo,检验所有关系
		if(!identify.equals(mat.getUserId())){
			response.setStatus(404);
			return;
		}
		String diskDir = config.getProperty("file_disk_dir");
		abs = (StringUtils.isNullOrEmpty(diskDir)?"":diskDir) + abs;
		try{
			FileToolsBar.readFileIntoStream(new File(abs),
					response.getOutputStream());
		}catch(IOException ex){
			throw new MessageRuntimeException(ex);
		}
	}
	/**
	 * 上传素材文件(限制为图片)
	 */
	@RequestMapping(value="/",method=RequestMethod.POST)
	@ResponseBody
	public Object upload(@RequestParam(value="pic",required=true)
			MultipartFile loadFile,HttpServletRequest request,HttpServletResponse response){
		if(null != loadFile && !loadFile.isEmpty()){
			if(!loadFile.getOriginalFilename().matches(".*[.](png|jpg|jpeg|bmp)$")){
				return new ResponseVO().error("502", config.get("502"));
			}
			InputStream in = null;
			String path = null;
			try{
				in = loadFile.getInputStream();
				path = saveFile.saveByDir(in
						,config.getProperty("mat_dir"));
			}catch(IOException io){
				throw new MessageRuntimeException(io);
			}
			MATFileVo fileVo = new MATFileVo(path
					,Calendar.getInstance().getTime(),identify);
			try{
				fileService.doSaveMATFile(fileVo);
			}catch(Exception ex){
				logger.info("deleting uploaded file.... path is "+path);
				saveFile.remove(path);
				throw new MessageRuntimeException(ex);
			}finally{
			}
			return new ResponseVO();
		}else{
			return new ResponseVO().error("501", config.get("501"));
		}
	}
	/**
	 * 获得素材文件列表
	 */
	@RequestMapping(value="/list",method=RequestMethod.GET)
	@ResponseBody
	public Object list(){
		//AuthUtils.getIdentify();
		List<MATFileVo> list = fileService.getMATFileList(identify);
		return new ResponseVO().setDatas(list);
	}
	@RequestMapping(value="/",method=RequestMethod.PUT)
	@ResponseBody
	public Object delete(@JsonModel List<String> ids){
		List<MATFileVo> vos = new ArrayList<MATFileVo>();
		for(String id : ids){
			MATFileVo mat = fileService.getMATFile(id);//获得素材文件的vo,检验所有关系
			if(!identify.equals(mat.getUserId())){
				return new ResponseVO().error("503", config.get("503"));//没有权限
			}
			vos.add(mat);
		}
		fileService.deleteMATFiles(vos);
		return new ResponseVO();
	}
}
